﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using CookComputing.XmlRpc;
using System.Collections.Generic;

namespace Pulog.Models.MetaWeblog
{
    [XmlRpcService(XmlEncoding = "UTF-8", Indentation = 2, UseStringTag = true, UseIntTag = true, UseIndentation = true)] 
    public class MetaWeblog : XmlRpcService, IMetaWeblog
    {

        #region Meta
        private readonly PostRepository postRepository = new PostRepository();
        #region Public Constructors

        public MetaWeblog()
        {
        }

        #endregion

        #region IMetaWeblog Members

        //string IMetaWeblog.AddPost(string blogid, string username, string password, Post post, bool publish)
        //{
        //    if (ValidateUser(username, password))
        //    {
        //        string id = string.Empty;

        //        Pulog.Models.Post p = new Pulog.Models.Post();
        //        p.Category = new Pulog.Models.Category() { categoryName = post.category[0] };
        //        p.authorID = int.Parse(post.userid);
        //        p.content = post.description;
        //        p.pubTime = post.dateCreated;


        //        postRepository.InsertPost(p);
        //        postRepository.Save();

        //        return id;
        //    }
        //    throw new XmlRpcFaultException(0, "User is not valid!");
        //}

        //bool IMetaWeblog.UpdatePost(string postid, string username, string password, Post post, bool publish)
        //{
        //    if (ValidateUser(username, password))
        //    {
        //        bool result = false;

        //        // TODO: Implement your own logic to add the post and set the result

        //        return result;
        //    }
        //    throw new XmlRpcFaultException(0, "User is not valid!");
        //}

        //Post IMetaWeblog.GetPost(string postID, string username, string password)
        //{
        //    if (ValidateUser(username, password))
        //    {
        //        return GetPost(postID);
        //    }
        //    throw new XmlRpcFaultException(0, "User is not valid!");
        //}

        //CategoryInfo[] IMetaWeblog.GetCategories(string blogid, string username, string password)
        //{
        //    if (ValidateUser(username, password))
        //    {
        //        List<CategoryInfo> categoryInfos = new List<CategoryInfo>();

        //        categoryInfos = GetCategories(blogid, username, password, "");

        //        return categoryInfos.ToArray();
        //    }
        //    throw new XmlRpcFaultException(0, "User is not valid!");
        //}

        //Post[] IMetaWeblog.GetRecentPosts(string blogid, string username, string password, int numberOfPosts)
        //{
        //    if (ValidateUser(username, password))
        //    {
        //        //Post[] posts = new Post[5];
        //        //Post p = new Post() { category = "s",  dateCreated = DateTime.Now, description = "<b>test</b>", link = "http://localhost:55054/Posts/Show/170", postid = "170", title = "title", userid = "1", slug = "slug", publish=true };
        //        //posts[0] = p;
               
        //        // TODO: Implement your own logic to get posts and set the posts

        //        //return posts;
        //        return GetRecentPosts(blogid, username, password, numberOfPosts);
        //    }
        //    throw new XmlRpcFaultException(0, "User is not valid!");
        //}

        //MediaObjectInfo IMetaWeblog.NewMediaObject(string blogid, string username, string password, MediaObject mediaObject)
        //{
        //    if (ValidateUser(username, password))
        //    {
        //        MediaObjectInfo objectInfo = new MediaObjectInfo();

        //        // TODO: Implement your own logic to add media object and set the objectInfo

        //        return objectInfo;
        //    }
        //    throw new XmlRpcFaultException(0, "User is not valid!");
        //}

        //bool IMetaWeblog.DeletePost(string key, string postid, string username, string password, bool publish)
        //{
        //    if (ValidateUser(username, password))
        //    {
        //        bool result = false;

        //        // TODO: Implement your own logic to delete the post and set the result

        //        return result;
        //    }
        //    throw new XmlRpcFaultException(0, "User is not valid!");
        //}

        //BlogInfo[] IMetaWeblog.GetUsersBlogs(string key, string username, string password)
        //{
        //    if (ValidateUser(username, password))
        //    {
        //        BlogInfo bi = new BlogInfo() { blogid = "1", blogName = "a", url = "http://localhost:1269/" };
        //        List<BlogInfo> infoList = new List<BlogInfo>();
        //        infoList.Add(bi);

        //        // TODO: Implement your own logic to get blog info objects and set the infoList

        //        return infoList.ToArray();
        //    }
        //    throw new XmlRpcFaultException(0, "User is not valid!");
        //}

        //UserInfo IMetaWeblog.GetUserInfo(string key, string username, string password)
        //{
        //    if (ValidateUser(username, password))
        //    {
        //        UserInfo info = new UserInfo();

        //        // TODO: Implement your own logic to get user info objects and set the info

        //        return info;
        //    }
        //    throw new XmlRpcFaultException(0, "User is not valid!");
        //}

        #endregion

        #region Private Methods

        private bool ValidateUser(string username, string password)
        {
            bool result = true;

            // TODO: Implement the logic to validate the user

            return result;
        }

        #endregion
        #endregion

        #region help methods

        /// <summary>
        /// metaWeblog.getRecentPosts
        /// </summary>
        /// <param name="blogID">always 1000 in BlogEngine since it is a singlar blog instance</param>
        /// <param name="userName">login username</param>
        /// <param name="password">login password</param>
        /// <param name="numberOfPosts">number of posts to return</param>
        /// <returns>array of post structs</returns>
        private Post[] GetRecentPosts(string blogID, string userName, string password, int numberOfPosts)
        {

            List<Post> sendPosts = new List<Post>();
            List<Pulog.Models.Post> posts = postRepository.GetPostsByNumbers(numberOfPosts);

            foreach (Pulog.Models.Post post in posts)
            {
                Post tempPost = new Post();

                tempPost.postid = post.postID.ToString(); 
                tempPost.title = post.title;
                tempPost.link = Helper.BlogURL + "/Posts/Show/" + post.postID;
                tempPost.description = post.content;
                
                tempPost.dateCreated = post.pubTime;
                //tempPost.publish = true;
                //tempPost.slug = post.slug;
                //tempPost.excerpt = "abc";
                //if (post.IsCommentsEnabled)
                //    tempPost.commentPolicy = "";
                //else
                //    tempPost.commentPolicy = "0";

                string cat = post.Category.categoryName;
                List<string> cats = new List<string>();
                cats.Add(cat);
                tempPost.categories = cats.ToArray<string>();

                sendPosts.Add(tempPost);
            }
            return sendPosts.ToArray();
        }

        /// <summary>
		/// metaWeblog.getPost
		/// </summary>
		/// <param name="postID">post guid in string format</param>
		/// <param name="userName">login username</param>
		/// <param name="password">login password</param>
		/// <returns>struct with post details</returns>
        internal Post GetPost(string postID)
		{

            Post sendPost = new Post();
			Models.Post post = postRepository.GetPostById(Convert.ToInt32(postID));

            sendPost.postid = post.postID.ToString();
			sendPost.dateCreated = post.pubTime;
			sendPost.title = post.title;
			sendPost.description = post.content;
            sendPost.link = Helper.BlogURL + "/Posts/Show/" + post.postID;
			//sendPost.slug = post.slug;

            string cat = post.Category.categoryName;
            List<string> cats = new List<string>();
            cats.Add(cat);
            sendPost.categories = cats.ToArray<string>();
			//sendPost.excerpt = post.Description;
			//if (post.IsCommentsEnabled)
			//	sendPost.commentPolicy = "1";
			//else
			//	sendPost.commentPolicy = "0";


			//sendPost.publish = post.IsPublished;

			//List<string> cats = new List<string>();
            //foreach (Models.Category cat in new CategoryRepository().GetCategoriesByPostId(Convert.ToInt32(postID)))
            //{
            //    cats.Add(cat.categoryName);
            //}
    //sendPost.categories = new CategoryRepository().GetCategoriesByPostId(Convert.ToInt32(postID));

            //List<string> tags = new List<string>();
            //for (int i = 0; i < post.Tags.Count; i++)
            //{
            //    tags.Add(post.Tags[i]);
            //}
            //sendPost.tags = tags;

			return sendPost;
		}

        /// <summary>
        /// metaWeblog.getCategories
        /// </summary>
        /// <param name="blogID">always 1000 in BlogEngine since it is a singlar blog instance</param>
        /// <param name="userName">login username</param>
        /// <param name="password">login password</param>
        /// <param name="rootUrl">The root URL.</param>
        /// <returns>array of category structs</returns>
        internal List<CategoryInfo> GetCategories(string blogID, string userName, string password, string rootUrl)
        {
            List<CategoryInfo> categories = new List<CategoryInfo>();

            foreach (Models.Category cat in postRepository.GetCategories())
            {
                CategoryInfo temp = new CategoryInfo();
                temp.categoryid = cat.categoryID.ToString();
                temp.title = cat.categoryName;
                temp.description = cat.categoryDesc; //cat.Description;
                temp.htmlUrl = rootUrl + "category/" + cat.categoryName;
                temp.rssUrl = rootUrl + "category/syndication.axd?category=" + cat.categoryName;
                categories.Add(temp);
            }

            return categories;
        }

        #endregion

        #region IMetaWeblog Members

        public object editPost(string postid, string username, string password, Post post, bool publish)
        {
            throw new NotImplementedException();
        }

        public CategoryInfo[] getCategories(string blogid, string username, string password)
        {
            throw new NotImplementedException();
        }

        public Post getPost(string postid, string username, string password)
        {
            if (ValidateUser(username, password))
            {
                return GetPost(postid);
            }
            throw new XmlRpcFaultException(0, "User is not valid!");
        }

        public Post[] getRecentPosts(string blogid, string username, string password, int numberOfPosts)
        {
            if (ValidateUser(username, password))
            {
                //Post[] posts = new Post[5];
                //Post p = new Post() { category = "s",  dateCreated = DateTime.Now, description = "<b>test</b>", link = "http://localhost:55054/Posts/Show/170", postid = "170", title = "title", userid = "1", slug = "slug", publish=true };
                //posts[0] = p;
               
                // TODO: Implement your own logic to get posts and set the posts

                //return posts;
                return GetRecentPosts(blogid, username, password, numberOfPosts);
            }
            throw new XmlRpcFaultException(0, "User is not valid!");
        }

        public string newPost(string blogid, string username, string password, Post post, bool publish)
        {
            if (ValidateUser(username, password))
            {
                string id = string.Empty;

                Pulog.Models.Post p = new Pulog.Models.Post();
                p.Category = new Pulog.Models.Category() { categoryName = post.categories[0] };
                p.authorID = int.Parse("1");
                p.content = post.description;
                p.title = post.title;
                p.password = "";
                p.pubTime = post.dateCreated;
                p.slug = post.title;

                postRepository.InsertPost(p);
                postRepository.Save();

                return id;
            }
            throw new XmlRpcFaultException(0, "User is not valid!");
        }

        public UrlData newMediaObject(string blogid, string username, string password, FileData file)
        {
            throw new NotImplementedException();
        }

        ///// <summary>
        ///// blogger.getUsersBlogs
        ///// </summary>
        ///// <param name="appKey">Key from application.  Outdated methodology that has no use here.</param>
        ///// <param name="userName">login username</param>
        ///// <param name="password">login password</param>
        ///// <param name="rootUrl">The root URL.</param>
        ///// <returns>array of blog structs</returns>
        //public List<BlogInfo> GetUserBlogs(string appKey, string userName, string password, string rootUrl)
        //{
        //    List<BlogInfo> blogs = new List<BlogInfo>();

        //    if (ValidateUser(userName, password))
        //    {

        //        BlogInfo temp = new BlogInfo();
        //        temp.url = rootUrl;
        //        temp.blogID = "1000";
        //        temp.blogName = Helper.BlogName;
        //        blogs.Add(temp);
        //    }
        //    return blogs;
        //}

        //#endregion

        //#region IMetaWeblog Members


        #endregion

        #region IMetaWeblog Members


        public bool DeletePost(string key, string postid, string username, string password, bool publish)
        {
            if (ValidateUser(username, password))
            {
                bool result = false;
                // TODO: Implement your own logic to delete the post and set the result
                return result;
            }
            return true;
        }

        public BlogInfo[] GetUsersBlogs(string key, string username, string password)
        {
            BlogInfo bi = new BlogInfo() { blogid = "1", blogName = "a", url = "http://localhost:1269/" };
            List<BlogInfo> infoList = new List<BlogInfo>();
            infoList.Add(bi);
            // TODO: Implement your own logic to get blog info objects and set the infoList

            return infoList.ToArray();
        }

        public UserInfo GetUserInfo(string key, string username, string password)
        {
            if (ValidateUser(username, password))
            {
                UserInfo info = new UserInfo();
                // TODO: Implement your own logic to get user info objects and set the info
                return info;
            }
            throw new XmlRpcFaultException(0, "User is not valid!");
        }

        #endregion
    }
}
